package com.enjoyor.soa.traffic.util.helper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: FormatHelper 
 * @Description: TODO(格式转化辅助类) 
 * @author xujianjun
 * @email xujianjun@enjoyor.net（根据自身情况修改）
 * @date 2017年6月6日 下午1:10:43
 */
public class FormatHelper{

	/**
	* @Title: toNum 
	* @Description: TODO(转化为整形数字) 
	* @param obj被转换对象
	* @return 捕获异常后返回0
	* @throws
	 */
	public static int toNum(Object obj){
		try {
			return Integer.parseInt(String.valueOf(obj));
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串格式转换整形数字错误！", ex);
			return 0;
		}
	}
	
	/**
	 * 
	* @Title: toFloat 
	* @Description: TODO(转化为浮点型数据) 
	* @param obj被转换对象
	* @return 捕获异常后返回0
	* @throws
	 */
	public static float toFloat(Object obj){
		try {
			return Float.parseFloat(String.valueOf(obj));
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串格式转换数字错误！", ex);
			return (float) 0;
		}
	}
	
	/**
	 * 
	* @Title: toDouble 
	* @Description: TODO(将对象转化为double型数据) 
	* @param obj被转换对象
	* @return 捕获异常后返回0.0
	* @throws
	 */
	public static Double toDouble(Object obj) {
		try {
			return Double.parseDouble(String.valueOf(obj));
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串转Double格式错误！", ex);
			return 0.0;
		}
	}
	
	/**
	 * 
	* @Title: toDate 
	* @Description: TODO(字符串转化为时间格式) 
	* @param str 字符串内容
	* @return 捕获异常后返回当前时间
	* @throws
	 */
	public static Date toDate(String str) {
		try {
			return TimeHelper.StringToDate(str, "yyyy-MM-dd");
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串转时间格式错误！", ex);
			return new Date();
		}
	}
	
	/**
	* @Title: toDate 
	* @Description: TODO(按照指定格式将字符串转化为时间格式) 
	* @param str时间字符串
	* @param param格式字符串
	* @return 捕获异常后返回当前时间
	* @throws
	 */
	public static Date toDate(String str,String param) {
		try {
			return TimeHelper.StringToDate(str, param);
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串转时间格式错误！", ex);
			return new Date();
		}
	}

	/**
	* @Title: toString 
	* @Description: TODO(字符串转化为字符串，过滤null情况) 
	* @param str 被转化字符串
	* @return 转化后字符串
	* @throws
	 */
	public static String toString(String str) {
		try {
			if (null == str) {
				str = "";
			}
			return str;
		} catch (Exception ex) {
			LoggerHelper.LOG.error("字符串格式转换错误！", ex);
			return "";
		}
	}
	
	 /**
     * 将val转换为类型toType的数据
     * @param val
     * @param toType 支持Integer/int、Long/long、Short/short、Byte/byte、
     * Double/double、Float/float、Boolean/boolean、
     * Date(支持特定format的字符串，如：yyyy-MM-dd HH:mm:ss、yyyy/MM/dd HH:mm:ss、yyyy-MM-dd等)
     * @return 转换失败返回 null
     */
    public static <T> T castTo(String val,Class<T> toType){
    	Object ret = null;
    	try{
    		if(val!=null&&!"".equals(val)){
		    	if(toType.equals(String.class)){
		    		ret = val;
				}else if(toType.equals(Integer.class)||toType.equals(int.class)){
					ret = Integer.parseInt(val);
				}else if(toType.equals(Long.class)||toType.equals(long.class)){
					ret = Long.parseLong(val);
				}else if(toType.equals(Short.class)||toType.equals(short.class)){
					ret = Short.parseShort(val);
				}else if(toType.equals(Byte.class)||toType.equals(byte.class)){
					ret = Byte.parseByte(val);
				}else if(toType.equals(Double.class)||toType.equals(double.class)){
					ret = Double.parseDouble(val);
				}else if(toType.equals(Float.class)||toType.equals(float.class)){
					ret = Float.parseFloat(val);
				}else if(toType.equals(Boolean.class)||toType.equals(boolean.class)){
					ret = Boolean.parseBoolean(val);
				}else if(toType.equals(Date.class)){
					//bug改正: new SimpleDateFormat("yyyyMMddHHmmss").parse("20180505155557894"); -->2018-05-06 07:59:54
					if(ret==null) try{ret = sdf1.get().parse(val.substring(0,sdf1.get().toPattern().length()));}catch(Throwable e){}
					if(ret==null) try{ret = sdf2.get().parse(val.substring(0,sdf2.get().toPattern().length()));}catch(Throwable e){}
					if(ret==null) try{ret = sdf3.get().parse(val.substring(0,sdf3.get().toPattern().length()));}catch(Throwable e){}
					if(ret==null) try{ret = sdf4.get().parse(val.substring(0,sdf4.get().toPattern().length()));}catch(Throwable e){}
					if(ret==null) try{ret = sdf5.get().parse(val.substring(0,sdf5.get().toPattern().length()));}catch(Throwable e){}
					if(ret==null) try{ret = sdf6.get().parse(val.substring(0,sdf7.get().toPattern().length()));}catch(Throwable e){}
					if(ret==null) try{ret = sdf7.get().parse(val.substring(0,sdf7.get().toPattern().length()));}catch(Throwable e){}
				}else if(toType.equals(oracle.spatial.geometry.JGeometry.class)){
					ret = GeomtryHelper.getJTring2Geom(val);
				}
    		}
    	}catch(Throwable ex){
			LoggerHelper.LOG.error("字符串转"+toType.getName()+"格式错误！", ex);
		}
    	return (T) ret;
    }
    static ThreadLocal<SimpleDateFormat> sdf1 = new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMddHHmmssSSS");} };
    static ThreadLocal<SimpleDateFormat> sdf2 = new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyyMMddHHmmss");} };
    static ThreadLocal<SimpleDateFormat> sdf3 = new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSSSSSSSS");} };
    static ThreadLocal<SimpleDateFormat> sdf4 = new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");} };
    static ThreadLocal<SimpleDateFormat> sdf5 = new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");} };
    static ThreadLocal<SimpleDateFormat> sdf6 = new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd");} };
    static ThreadLocal<SimpleDateFormat> sdf7 = new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy/MM/dd");} };
    
    
    /**
     * 判断字符是否是中文
     *
     * @param c 字符
     * @return 是否是中文
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
 
    /**
     * 判断字符串是否是乱码
     *
     * @param strName 字符串
     * @return 是否是乱码
     */
    public static boolean isMessyCode(String strName) {
    	Pattern p = Pattern.compile("\\s*|t*|r*|n*");
        Matcher m = p.matcher(strName);
        String after = m.replaceAll("");
        String temp = after.replaceAll("\\p{P}", "");
        char[] ch = temp.trim().toCharArray();
        float chLength = ch.length;
        float count = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (!Character.isLetterOrDigit(c)) {
                if (!isChinese(c)) {
                    count = count + 1;
                }
            }
        }
        float result = count / chLength;
        if (result > 0.4) {
            return true;
        } else {
            return false;
        }
 
    }

	public static boolean isInteger(String str) {  
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
		return pattern.matcher(str).matches();  
	}
	
    public static void main(String[] args) {
        System.out.println(isMessyCode("Ã©Å¸Â©Ã©Â¡ÂºÃ¥Â¹Â³"));
        System.out.println(isMessyCode("你好"));
    }
}
